package com.renwei.yunlong.activity.work;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.PoiListAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.LocationBean;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.RoundView;
import com.renwei.yunlong.http.Api;

import java.util.List;

/**
 * Project :  yunna.
 * Package name: com.renwei.yunlong.activity.work
 * Created by :  Benjamin.
 * Created time: 2018/1/16 15:18
 * Changed by :  Benjamin.
 * Changed time: 2018/1/16 15:18
 * Class description:
 *
 * @author Benjamin
 */

public class SignConfirmActivity extends BaseActivity implements View.OnClickListener, SensorEventListener, PoiListAdapter.PoiSelectListener {


    private MapView mapView;
    private ImageView ivBack;
    private ImageView ivLoca;
    private ImageView ivClean;
    private RecyclerView recyclerView;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    private int mCurrentDirection = 0;
    private LatLng llMe;
    private SensorManager mSensorManager;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private List<Marker> markers;
    private Marker meMarker;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    private List<LocationBean.RowsBean> mList;
    private PoiListAdapter poiListAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_confirm_activity);
        initView();
    }


    private void initView() {
        mapView = findViewById(R.id.bmapView);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        ivLoca = findViewById(R.id.iv_loca);
        ivLoca.setOnClickListener(this);
        ivClean = findViewById(R.id.iv_clean);
        ivClean.setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerView);
        //初始化pop
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        poiListAdapter = new PoiListAdapter(this);
        poiListAdapter.setListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(SignConfirmActivity.this));
        recyclerView.setAdapter(poiListAdapter);
        // 隐藏logo
        View child = mapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
            /*mPoiSearch.*/
        }
        // 隐藏 比例尺和加减号
        mapView.showScaleControl(false);
        mapView.showZoomControls(false);
        mBaiduMap = mapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        // 设置是否需要地址信息，默认为无地址
        option.setIsNeedAddress(true);
        // 设置是否需要返回位置语义化信息，可以在BDLocation.getLocationDescribe()中得到数据，ex:"在天安门附近"，
        // 可以用作地址信息的补充
        option.setIsNeedLocationDescribe(true);
        // 设置是否需要返回位置POI信息，可以在BDLocation.getPoiList()中得到数据
        option.setIsNeedLocationPoiList(true);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_back:
                this.finish();
                break;
            case R.id.iv_loca:
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(new LatLng(mCurrentLat, mCurrentLon))
                        .zoom(16)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.animateMapStatus(mMapStatusUpdate);
                break;
            case R.id.iv_clean:
                break;
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


    @Override
    public void poiSelect(PoiInfo info) {
        poiListAdapter.changeSelectItem(info.uid);
        //uid是POI检索中获取的POI ID信息
        Intent intent = new Intent();
        intent.putExtra("address", String.valueOf(info.address + info.name));
        setResult(999, intent);
        this.finish();
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner extends BDAbstractLocationListener {


        @Override
        public void onReceiveLocation(BDLocation location) {
            // map icon_work_watch 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();

            if (llMe == null) {
                /**
                 * 搜索位置点周边POI
                 */
                llMe = new LatLng(mCurrentLat, mCurrentLon);
                GeoCoder geoCoder = GeoCoder.newInstance();
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

                    }

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                        List<PoiInfo> poiInfos = reverseGeoCodeResult.getPoiList();//poi列表'
                        if (UtilList.getCount(poiInfos) > 0) {
                            poiListAdapter.refresh(poiInfos);
                        } else {
                            recyclerView.setVisibility(View.GONE);
                        }
                    }
                });
                geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(llMe));

                String url = "1".equals(companyType) ? Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar()
                        : Api.$().SERVICE_FILE_URL + serviceLoginBean.getRows().getAvatar();
                addMapOver(false, llMe, R.mipmap.icon_map_loc_me, url, null);
            } else {
                llMe = new LatLng(mCurrentLat, mCurrentLon);
                if (meMarker != null) {
                    meMarker.setPosition(llMe);
                }
            }
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(16.0f);
                // 设置地图参数
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }


    }

    private void addMapOver(final boolean isFirst, final LatLng latLng, final int imgRes, final String url, final LocationBean.RowsBean bean) {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.view_map_icon, null);
        RelativeLayout rlMap = view.findViewById(R.id.rl_map);
        rlMap.setBackgroundResource(imgRes);
        final RoundView rvMap = view.findViewById(R.id.rv_head);
        Glide.with(mContext).load(url)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        rvMap.setImageResource(R.mipmap.icon_header_default);
                        BitmapDescriptor locMe = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                        MarkerOptions ooMe = new MarkerOptions().position(latLng).icon(locMe)
                                .zIndex(1).draggable(true);
                        Marker marker = (Marker) mBaiduMap.addOverlay(ooMe);
                        if (bean != null) {
                            mList.add(bean);
                            markers.add(marker);
                        } else {
                            meMarker = marker;
                        }
                        marker.setToTop();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (isFirst) {
                                    BitmapDescriptor locMe = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                                    MarkerOptions ooMe = new MarkerOptions().position(latLng).icon(locMe)
                                            .zIndex(1).draggable(true);

                                    Marker marker = (Marker) mBaiduMap.addOverlay(ooMe);
                                    if (bean != null) {
                                        mList.add(bean);
                                        markers.add(marker);
                                    } else {
                                        meMarker = marker;
                                    }
                                    marker.setToTop();
                                } else {
                                    addMapOver(true, latLng, imgRes, url, bean);
                                }
                            }
                        }, 500);
                        return false;
                    }
                }).into(rvMap);
    }

    /**
     * 把View转换成Bitmap类型
     *
     * @return
     * @paramaddViewContent要转换的View
     */
    public Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());


        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        return bitmap;
    }


    @Override
    public void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(SignConfirmActivity.this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();
    }


    public static void OpenActivity(Context context) {
        Intent intent = new Intent(context, SignConfirmActivity.class);
        ((Activity) context).startActivityForResult(intent, 999);
    }
}